/*
字符设备的设备号资源

安装次模块，将
    在/proc/devices文件里生成设备(chrdev_region)及其主设备号(255)
*/

#include "linux/init.h"
#include "linux/module.h"
#include "linux/fs.h"

static dev_t chrdev_id = 0;
static uint32_t count = 1; // 字符设备的个数
static uint8_t registered = 0;

static int __init chrdev_region_init(void)
{
    int ret = -1;

    printk("file=%s,fun=%s,line=%d\n", __FILE__, __FUNCTION__, __LINE__);

    // 初始化设备号
    chrdev_id = MKDEV(255, 0);
    printk("chrdev_id[MAJOR=%u,MINOR=%u]\n", MAJOR(chrdev_id), MINOR(chrdev_id));

    // 注册字符设备的设备号
    ret = register_chrdev_region(chrdev_id, count, "chrdev_region");
    if (ret < 0)
    {
        printk("register_chrdev_region error\n");
        return -1;
    }
    printk("register_chrdev_region succeed\n");
    printk("chrdev_id[MAJOR=%u,MINOR=%u]\n", MAJOR(chrdev_id), MINOR(chrdev_id));

    registered = 1;

    return 0;
}

static void __exit chrdev_region_exit(void)
{
    printk("file=%s,fun=%s,line=%d\n", __FILE__, __FUNCTION__, __LINE__);

    if (registered)
    {
        unregister_chrdev_region(chrdev_id, count);

        printk("unregister_chrdev_region succeed\n");
    }
}

module_init(chrdev_region_init);
module_exit(chrdev_region_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("lxz");